package com.hzlj.position.job.notice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.fz.common.base.core.JsonUtils;
import com.hzlj.common.message.common.dto.message.MessageNoticeResultDTO;
import com.hzlj.common.message.common.dto.message.MessageNoticeUserDTO;
import com.hzlj.common.message.common.util.MessageRestUtil;
import com.hzlj.position.job.common.model.NoticeJob;
import com.hzlj.position.job.rest.StatRest;
import com.hzlj.position.locate.common.dto.reportCommon.AbnMissingStatDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class AbnMissingNoticeJob implements BaseNoticeJob {
    @Resource
    private StatRest statRest;

    @Override
    public void notice(List<NoticeJob> jobs) {
        for (NoticeJob job : jobs) {
            Date now = new Date();
            List<AbnMissingStatDTO> stats = statRest.statAbnMissing(job.getParams(), job.getJgCode(), now);
            if (ObjectUtil.isEmpty(stats)) {
                continue;
            }

            //发送消息
            for (AbnMissingStatDTO stat : stats) {
                try {
                    Integer abnMissingDays = job.getParams().getAbnMissingDays();
                    Map<String, Object> params = BeanUtil.beanToMap(stat);
                    params.put("belongDay", DateUtil.formatDate(now));
                    params.put("abnMissingDays", job.getParams().getAbnMissingDays());
                    params.put("spotCheckTime", DateUtil.formatDateTime(now));

                    List<MessageNoticeResultDTO> result = MessageRestUtil.noticeQueryUsers(
                            abnMissingDays == 1 ? "abn-missing-gzry" : "abn-missing-lx-gzry",
                            RandomUtil.randomNumbers(10),
                            params,
                            MessageNoticeUserDTO.of(true, stat.getJgCode(), job.getRoles()));
                    log.info("失联人员每日通知:notice={},stat={}", JsonUtils.obj2json(result), JsonUtils.obj2json(stat));
                } catch (Exception e) {
                    log.error("失联人员每日通知通知异常:notice={}", JsonUtils.obj2json(stat));
                }
            }

        }
    }
}
